<template>
    <view class="user-page">
      <view :style="{ height: navBarHeight + 'px' }"></view>
      <view class="user-header" >
          <image
            class="user-avatar"
            :src="userInfo.avatarUrl"
            mode="scaleToFill"
            @click="getUserProfile"
          />
      </view>
      <auth-modal :show="showLoginModal" @close="hideModal" @success="surcessModal" />
      <ul class="user-info">
        <li class="user-info-item" :class="{'first' : index === 0, 'second': index === 1 }" v-for="(item, index) in userList" :key="index" @click="item.click ? item.click() : ''">
          <view>
            <text class="user-info-title">{{ item.title }}</text>
            <text class="username" :class="{ 'gray': item.gray }">{{ item.value }}</text>
          </view>
          <view>
            <text class="uid" v-if="item.more">></text>
          </view>
        </li>
        <!-- <contact-button
          class="floating-kefu"
          session-from="user_page"
          button-text=""
          show-message-card="false"
        >
        </contact-button> -->
        <button class="floating-kefu" open-type="contact">

        </button>
      </ul>
    </view>
</template>
<script lang="ts" setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { request, uploadFiles } from '../utils/request'
import authModal from '@/components/auth-modal/auth-modal.vue'
const platform = ref(1) // 1: 微信小程序，2: 抖音小程序
const showLoginModal = ref(false)
const navBarHeight = ref(0)
const userInfo = ref({
  nickName: '',
  avatarUrl: '/static/authur.jpeg',
  videoId: '',
  liveId: ''
})
const userList = ref([
  {
    title: '昵称',
    value: userInfo.value.nickName,
    url: '',
    more: false,
    click: () => { goEditNickname() }
  },
  {
    title: '官方账号',
    value: platform.value == 1 ? '视频号' : '抖音号',
    url: '',
    more: true,
    gray: true,
    click: () => { goVideoPage() }
  },
  {
    title: '官方直播',
    value: userInfo.value.liveId || '线下精彩比赛',
    url: '',
    more: true,
    gray: true,
    click: () => { goLivePage() }
  },
  // {
  //   title: '联系我们',
  //   value: '微信企业号',
  //   more: false,
    // click: () => { goPage('/pages/user/concatus') },
    // click: () => {
    //   if (platform.value == 1) {
          // #ifdef MP-WEIXIN
          // 企业微信客服
          // wx.openCustomerServiceChat({
          //   extInfo: {
          //     url: 'https://work.weixin.qq.com/kfid/kfcabd707a1b813484a' // 替换为真实链接
          //   },
          //   corpId: 'wwf475f16326f89cc7', // 替换为你的企业微信CorpID
          //   success(res) {
          //     console.log('打开成功', res)
          //   },
          //   fail(err) {
          //     console.error('打开失败', err)
          //   }
          // })
          // #endif
    //   }
    // }
  // },
  {
    title: '反馈建议',
    value: '你的反馈很重要',
    more: true,
    gray: true,
    click: () => { goPage('/pages/user/suggestion') },
  }
])
const getNavHeight = () => {
  const systemInfo = uni.getSystemInfoSync()
  const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
  // 状态栏高度
  const statusBarHeight = systemInfo.statusBarHeight || 20
  // 胶囊按钮高度
  const capsuleHeight = menuButtonInfo.height || 32
  // 胶囊与状态栏的间距
  const topGap = menuButtonInfo.top - statusBarHeight
  // 整个自定义导航栏高度
  navBarHeight.value = (statusBarHeight + capsuleHeight + topGap * 2) - 44
}
function goPage(url: string) {
  uni.navigateTo({ url })
}
// const goSuccuage = () => {
//   const token = uni.getStorageSync('token');
//   if (!token) {
//     showLoginModal.value = true
//   } else {
//     goPage('/pages/user/suggestion')
//   }
// }
const getUserProfile = () => {
  const token = uni.getStorageSync('token');
  const userInfos = uni.getStorageSync('userInfo')
  if (!token) {
    showLoginModal.value = true
    return
  }
  console.log('token', token)
  uni.chooseMedia({
    count: 1,
    mediaType: ['image'],
    sourceType: ['album', 'camera'],
    success (res) {
      console.log('选择的图片', res)
      const avatarUrl = res.tempFiles[0].tempFilePath
      uploadFiles({
        url: `/upload/img`,
        filePath: avatarUrl,
        name: 'file',
        header: {
          'Content-Type': 'multipart/form-data'
        },
        formData: {
          folder: avatarUrl,
          file: res
        }
      }).then(async (res: any) => {
        if(res.code !== 200) {
          uni.showToast({
            title: res.data.message || '上传失败',
            icon: 'none',
            duration: 3000
          })
          return
        }
        await request({
          url: `/user/update/${userInfos.id}`,
          method: 'post',
          data: {
            avatarUrl: res.data
          }
        }).then(async (res2) => {
          if(res2.code !== 200) {
            uni.showToast({
                title: res2.data.message || '设置失败',
                icon: 'none',
                    duration: 3000
                })
                return
            }
          userInfo.value.avatarUrl = res.data
          await getUserInfo()
        })
      })
    },
    fail(err) {
      console.error('选择失败', err)
    }
  })
}
const getUserInfo = async() => {
    await request({
        url: '/user/info',
        method: 'POST',
        data: {}
    }).then(res => {
      if(res.code !== 200) {
        uni.showToast({
          title: res.data.message || '获取失败',
          icon: 'none',
                  duration: 3000
        })
        return
      }
      uni.setStorageSync('userInfo', res.data)
    })
}
const hideModal = () => {
  showLoginModal.value = false
}
const surcessModal = () => {
  showLoginModal.value = false
  setTimeout(() => {
    const userInfos = uni.getStorageSync('userInfo')
    userInfo.value = userInfos
         userList.value = [
      {
        title: '昵称',
        value: userInfo.value.nickName,
        url: '',
        more: false,
        click: () => { goEditNickname() }
      },
      {
        title: '官方账号',
        value: platform.value == 1 ? '视频号' : '抖音号',
        url: '',
        more: true,
        gray: true,
        click: () => { goVideoPage() }
      },
      {
        title: '官方直播',
        value: userInfo.value.liveId || '线下精彩比赛',
        url: '',
        more: true,
         gray: true,
        click: () => { goLivePage() }
      },
      // {
      //   title: '联系我们',
      //   value: '微信企业号',
      //   more: false,
      //   click: () => { goPage('/pages/user/concatus') },
      // },
      {
        title: '反馈建议',
        value: '你的反馈很重要',
        more: true,
        gray: true,
        click: () => { goPage('/pages/user/suggestion') },
      }
    ]
    console.log('userInfo', userInfo.value)
  }, 500)
}

const goLivePage = () => {
  // 1: 微信小程序，2: 抖音小程序
  if (platform.value == 1) {
    if (typeof wx.openChannelsUserProfile !== 'function') {
      uni.showToast({ title: '微信版本过低', icon: 'none', duration: 3000 })
      return
    }
    wx.getChannelsLiveInfo({
      finderUserName: userInfo.value.videoId, // 视频号 ID（如：sphsf823sfw）
      success(res) {
        console.log('直播间信息', res)
        wx.openChannelsLive({
            finderUserName: userInfo.value.videoId, // 你的直播间 ID，必须是字符串
             success(res) {
               console.log('直播间打开成功', res)
             },
             fail(err) {
               console.error('打开失败', err)
            }
        })

      },
      fail(err) {
        console.error('获取失败', err)
      }
    })
  } else {
    tt.openAwemeLive({
      roomId: userInfo.value.liveId, // 你的直播间 ID，必须是字符串
      success(res) {
        console.log('直播间打开成功', res)
      },
      fail(err) {
        console.error('打开失败', err)
      }
    })
  }
}

const goVideoPage = () => {
  // 1: 微信小程序，2: 抖音小程序
  if (platform.value == 1) {
    if (typeof wx.openChannelsUserProfile !== 'function') {
      uni.showToast({ title: '微信版本过低', icon: 'none', duration: 3000 })
      return
    }

    wx.openChannelsUserProfile({
      finderUserName: userInfo.value.videoId, // 视频号 ID（如：sphsf823sfw）
      success() {
        console.log('打开视频号主页成功')
      },
      fail(err) {
        console.error('打开失败', err)
        uni.showToast({ title: '打开失败', icon: 'none', duration: 3000 })
      }
    })
  } else {
    // tt.openUserProfile({
    //   userId: userInfo.value.videoId,  // 这里填入你想要跳转的抖音用户ID
    //   success(res) {
    //     console.log('跳转成功', res);
    //   },
    //   fail(err) {
    //     console.error('跳转失败', err);
    //   }
    // });
    uni.showToast({ title: '暂不支持', icon: 'none', duration: 3000 })
  }
}
const getVideoId = async() => {
  await request({
    url: '/official/videoid',
    method: 'POST',
    header: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: {
      platform: platform.value
    }
  })
  .then((res: any) => {
    if(res.code !== 200) {
			uni.showToast({
				title: res.data.message || '获取失败',
				icon: 'none',
        duration: 3000
			})
			return;
		}
    userInfo.value.videoId = res.data
  })
  .catch((err: any) => {
    console.log(err)
  })
}

const getLiveId = async() => {
  await request({
    url: '/official/liveid',
    method: 'POST',
    header: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: {
      platform: platform.value
    }
  })
  .then((res: any) => {
    if(res.code !== 200) {
			uni.showToast({
				title: res.data.message || '获取失败',
				icon: 'none',
        duration: 3000
			})
			return;
		}
    userInfo.value.liveId = res.data
  })
}
const goEditNickname = () => {
  const token = uni.getStorageSync('token');
  if (!token) {
    showLoginModal.value = true
  } else {
    goPage('/pages/user/editNickname')
  }
}
const handleNicknameUpdate = async() => {
  console.log('昵称更新')
  platform.value = uni.getSystemInfoSync().uniPlatform === 'mp-weixin' ? 1 : 2
  await getUserInfo()
  const storedUser = uni.getStorageSync('userInfo')
  if (storedUser) {
      userInfo.value = storedUser
      userList.value = [
        {
          title: '昵称',
          value: userInfo.value.nickName,
          url: '',
          more: false,
          click: () => { goEditNickname() }
        },
        {
          title: '官方账号',
          value: platform.value == 1 ? '视频号' : '抖音号',
          url: '',
          more: true,
          gray: true,
          click: () => { goVideoPage() }
        },
        {
          title: '官方直播',
          value: userInfo.value.liveId || '线下精彩比赛',
          url: '',
          more: true,
          gray: true,
          click: () => { goLivePage() }
        },
        // {
        //   title: '联系我们',
        //   value: '微信企业号',
        //   more: false,
        //   click: () => { goPage('/pages/user/concatus') },
        // },
        {
          title: '反馈建议',
          value: '你的反馈很重要',
          more: true,
          gray: true,
          click: () => { goPage('/pages/user/suggestion') },
        }
      ]
      getVideoId()
      getLiveId()
  }
}
onMounted(() => {
  getNavHeight()
  handleNicknameUpdate()
  // const storedUser = uni.getStorageSync('userInfo')
  // uni.$on('nicknameUpdated', handleNicknameUpdate)
  // platform.value = uni.getSystemInfoSync().uniPlatform === 'mp-weixin' ? 1 : 2
  // if (storedUser) {
  //   userInfo.value = storedUser
  //   userList.value = [
  //     {
  //       title: '昵称',
  //       value: userInfo.value.nickName,
  //       url: '',
  //       more: false,
  //       click: () => { goEditNickname() }
  //     },
  //     {
  //       title: '官方账号',
  //       value: userInfo.value.videoId || '视频号/抖音号',
  //       url: '',
  //       more: true,
  //       click: () => { goVideoPage() }
  //     },
  //     {
  //       title: '官方直播',
  //       value: userInfo.value.liveId || '线下精彩比赛',
  //       url: '',
  //       more: true,
  //       gray: true,
  //       click: () => { goLivePage() }
  //     },
  //     {
  //       title: '联系我们',
  //       value: '微信企业号',
  //       more: false,
  //       click: () => { goPage('/pages/user/concatus') },
  //     },
  //     {
  //       title: '反馈建议',
  //       value: '你的反馈很重要',
  //       more: true,
  //       gray: true,
  //       click: () => { goPage('/pages/user/suggestion') },
  //     }
  //   ]
  //   getVideoId()
  //   getLiveId()
  // }
})

onUnmounted(() => {
  uni.$off('nicknameUpdated', handleNicknameUpdate)
})
</script>
<style scoped>
.floating-kefu{
  position: fixed;
  bottom: 15%;
  right: 20rpx;
  width: 90rpx;
  height: 90rpx;
  border: none !important;
  z-index: 999;
  background-image: url('/static/kefu.png'); /* 替换为你自己的图标路径 */
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
}

.floating-kefu {
  /* 自定义样式 */
  border: none;
  box-shadow: none;
  background-color: transparent;
}

/* 去除小程序原生点击阴影 */
.floating-kefu::after {
  border: none !important;
  background: transparent !important;
}
.user-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 0 20rpx;
}

.user-header {
  display: flex;
  justify-content: center;
  height: 390rpx;

}

.user-avatar {
  width: 150rpx;
  height: 150rpx;
  border-radius: 50%;
  border: 1px solid #ccc;
  margin-top: 140rpx;
}
.user-info {
  border-radius: 10rpx;
  color: #7c7d7c;
  font-size: 30rpx;
}
.user-info-item{
  height: 100rpx;
  line-height: 100rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1rpx solid #f6f6f6;
  background-color: #fff;
  padding: 0 20rpx;
}
.user-info-item .title {
}
.user-info-title{
  width: 180rpx;
  display: inline-block;
}
.user-info .username {
  color: #666666;
}
.gray{
  color: #ccc !important;
}
.uid{
    font-size: 30rpx;
    color: #b4b4b4;
    display: inline-block;
}
.first {
  margin-bottom: 15rpx;
  border-radius: 10rpx;
}
.second {
  border-radius: 10rpx 10rpx 0 0;
}
</style>